package com.controller;

import cn.dsna.util.images.ValidateCode;
import com.annotation.ContentType;
import com.entity.Message;
import com.entity.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.utils.Base64Utils;
import com.utils.Constants;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;

/**
 * @ProjectName: shop
 * @Author: Jsx
 * @Time: 2020/8/30 13:22
 * @Description:
 */
@WebServlet("/user")
public class UserController extends BaseController {
    /**
     * 检查账号是否存在
     * @param request
     * @param response
     * @return
     */
    @ContentType("application/json;charset=utf-8")
    public Message checkUser(HttpServletRequest request , HttpServletResponse response) throws SQLException {
        //1.获取请求参数
        String username = request.getParameter("username");
        //2.调用业务逻辑
        UserService userService = new UserServiceImpl();
        Message message = userService.checkUser(username);
        //3.响应
        return message;
    }

    /**
     * 用户注册
     * @param request
     * @param response
     * @return
     */
    public String register(HttpServletRequest request , HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, SQLException {
        //1.获取请求参数
        // key  value  key value
        Map<String, String[]> map = request.getParameterMap();
        //将请求参数封装到实体类  更符合面向对象的思想
        //  input name的值  =====   http请求参数key    ====   map key  ===== 实体类的属性 驼峰式   ==不保证==  数据库列 _
        User user = new User();
        BeanUtils.populate(user,map);
        //2.调用业务逻辑
        UserService userService = new UserServiceImpl();
        int status = userService.register(user);

        //3.响应
        if (status == Constants.MESSAGE_FAIL) {
            request.getSession().setAttribute("register","注册失败,请稍后再试");
            return Constants.REDIRECT_ACTION + request.getContextPath() + "/register.jsp";
        }
        return Constants.REDIRECT_ACTION + request.getContextPath() + "/registerSuccess.jsp";
    }

    /**
     * 用户激活
     * @param request
     * @param response
     * @return
     * @throws SQLException
     */
    public String active(HttpServletRequest request , HttpServletResponse response) throws SQLException {

        //1.获取请求参数
        //激活码
        String code = request.getParameter("c");

        //2.调用业务逻辑
        UserService userService = new UserServiceImpl();
        int status = userService.activeUser(code);

        //3.响应数据
        if (status == Constants.ACTIVE_SUCCESS) {
            return Constants.REDIRECT_ACTION + request.getContextPath() + "/login.jsp";
        }

        HttpSession session = request.getSession();

        if (status == Constants.HASED_ACTIVE) {
            session.setAttribute("msg","账号已经激活,请勿重复激活！");
        }else{
            session.setAttribute("msg","激活失败,请稍后再试！");
        }

        return  Constants.REDIRECT_ACTION + request.getContextPath() + "/message.jsp";
    }

    /**
     * 图片验证码功能
     * @param request
     * @param response
     */
    @ContentType("image/png")
    public void retImg(HttpServletRequest request , HttpServletResponse response) throws IOException {

        ValidateCode validateCode = new ValidateCode(90,45,1,5);
        //返回图片上面的正确字符串
        String code = validateCode.getCode();
        HttpSession session = request.getSession();
        session.setAttribute("code",code);

        ServletOutputStream outputStream = response.getOutputStream();

        validateCode.write(outputStream);
    }

    /**
     * 登录功能
     * @param request
     * @param response
     * @return
     */
    public String login(HttpServletRequest request , HttpServletResponse response) throws SQLException {
        //1.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //用户输入
        String code = request.getParameter("code");
        //是否自动登录
        String auto = request.getParameter("auto");


        HttpSession session = request.getSession();
        String rCode = (String)session.getAttribute("code");
        //2.调用业务逻辑

        //1.比验证码

        if (rCode.equalsIgnoreCase(code))
        {
            //验证码正确
            UserService userService = new UserServiceImpl();
            User user = userService.login(username,password);

            if (user != null)
            {
                //查到了
                if (user.getUstatus() == Constants.ACTIVE_SUCCESS) {

                    //可以登录

                    session.setAttribute("user", user);

//                    if (auto != null) {
//                        //自动登录
//                        Cookie cookie = new Cookie("user", user.getUsername()+"_"+user.getUpassword());
//                        cookie.setPath(request.getContextPath());
//                        cookie.setMaxAge(2*7*24*60*60);
//                        response.addCookie(cookie);
//                    }
                    if (auto == null){
                        //没有勾选！
                        //将本地浏览器的存储的cookie'清空'
                        Cookie cookie = new Cookie(Constants.AUTO_NAME,"");
                        cookie.setPath("/");
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }else{
                        //自定登录数据库存储 2周
                        String content = username+ Constants.FLAG+password;
                        content = Base64Utils.encode(content);
                        Cookie cookie = new Cookie(Constants.AUTO_NAME,content);
                        cookie.setPath("/");
                        cookie.setMaxAge(14*24*60*60);
                        response.addCookie(cookie);
                    }


                    return Constants.REDIRECT_ACTION + "/index.jsp";

                }else{
                    session.setAttribute("msg","账号未激活，请激活后在登录！！");
                    return Constants.REDIRECT_ACTION + request.getContextPath()+"/login.jsp";
                }

            }else{
                //没有查到
                session.setAttribute("msg","账号或者密码错误！");
                return Constants.REDIRECT_ACTION + request.getContextPath()+"/login.jsp";
            }


        }else{

            session.setAttribute("msg","验证码错误！");
            return Constants.REDIRECT_ACTION + request.getContextPath()+"/login.jsp";
        }

    }

    /**
     * 注销登录功能
     * @param request
     * @param response
     * @return
     */
    public String logOut(HttpServletRequest request , HttpServletResponse response){

        //清空session
        request.getSession().invalidate();

        //结束用户的cookie生命
        Cookie autocookie = new Cookie("auto", "");

        autocookie.setMaxAge(0);
        response.addCookie(autocookie);

        return Constants.REDIRECT_ACTION + request.getContextPath() + "/index.jsp";
    }
}
